package org.dong.Control;


import org.dong.Tool.ApplicationUtil;
import org.dong.Tool.BarcodeGeneratorUtil;
import org.dong.Tool.Data;
import org.dong.pojo.*;
import org.dong.pojo.qo.OrderQo;
import org.dong.service.MealService;
import org.dong.service.OrderService;
import org.dong.service.ProjectService;
import org.dong.service.UserService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class OrderControl {

    @PostMapping("/Order/getOrderList")
    public Dto getOrderList(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Dto dto = new Dto();


        String sDate = req.getParameter("sdate");
        String eDate = req.getParameter("edate");
        String sName = req.getParameter("sname");
        String sCardId = req.getParameter("scardid");
        String sMeal = req.getParameter("smeal");
        Integer page = Integer.parseInt(req.getParameter("page"))-1;

        if(page <0){
            page =  0;
        }else{
            page = page *5;
        }


        OrderService orderService = (OrderService) ApplicationUtil.getContext().getBean("orderService");

        List<OrderQo> orderList = orderService.getOrderList(sDate,eDate,sName,sCardId,sMeal,page);
        //获取总条数
        Integer orderCount = orderService.getOrderCount(sDate, eDate, sName, sCardId, sMeal);


        Map<String, Object> datas = new HashMap<String, Object>();
        datas.put("order", orderList);
        datas.put("count", orderCount);
        dto.setDatas(datas);
        dto.setErrMsg("订单列表");
        dto.setStatusCode(200);

        return dto;
    }

    @PostMapping("/Order/getOrderInfo")
    public Dto getOrderInfo(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Dto dto = new Dto();
        AdminUser adminUser = (AdminUser) req.getSession().getAttribute("user");
        int id = Integer.parseInt(req.getParameter("id"));

        //先查询订单信息
        OrderService orderService = (OrderService) ApplicationUtil.getContext().getBean("orderService");
        final Order orderInfo = orderService.getOrderInfo(id);
        if(orderInfo != null){
            //查询用户信息
            final UserService userService = (UserService)ApplicationUtil.getContext().getBean("userService");
            final User user = userService.getUser(null, orderInfo.getUserId(),null);
            //查询套餐对应的体检项目
            ProjectService projectService = (ProjectService) ApplicationUtil.getContext().getBean("projectService");

            List<Project> projectList = projectService.getProjectList(orderInfo.getMealId());


            if(user != null && projectList != null){
                OrderQo orderQo = new OrderQo();
                orderQo.setOrderName(orderInfo.getOrderName());
                orderQo.setOrderSn(orderInfo.getOrderSn());
                orderQo.setQrcode(orderInfo.getQrcode());
                orderQo.setRealName(user.getRealName());
                orderQo.setCardId(user.getCardId());
                orderQo.setProjects(projectList);

                Map<String, Object> datas = new HashMap<String, Object>();
                datas.put("order", orderQo);
                dto.setDatas(datas);
                dto.setErrMsg("订单详情");
                dto.setStatusCode(200);
            }else{

                dto.setErrMsg("没有找到对应的用户和套餐");
                dto.setStatusCode(201);

            }

        }else{
            dto.setErrMsg("没有找到订单");
            dto.setStatusCode(201);
        }

        return dto;
    }

    @PostMapping("/Order/addOrder")
    public Dto addOrder(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Dto dto = new Dto();
        AdminUser adminUser = (AdminUser) req.getSession().getAttribute("user");
        String realname = req.getParameter("realname");
        String cardId = req.getParameter("cardId");
        String mealId = req.getParameter("mealId");
        String phone = req.getParameter("phone");
        String sex = req.getParameter("sex");

        System.out.println(req.getParameter("cardId"));
        int userId = 0;
        //判断用户是否存在
        UserService userService = (UserService)ApplicationUtil.getContext().getBean("userService");
        User user = userService.getUser(cardId,null,null);

        if(user != null){
            //获取id

            userId = user.getId();
        }else{
            user = new User();
            user.setCreateTime(BigDecimal.valueOf(System.currentTimeMillis()/1000));
            user.setPassword(Data.getMD5Hash("123456"));
            user.setRealName(realname);
            user.setCardId(cardId);
            user.setStatus(1);
            user.setPhone(phone);
            user.setSex(Integer.parseInt(sex));
            //生成用户
            final Integer integer = userService.addUser(user);
            userId = user.getId();
        }

        //查询套餐是否存在
        MealService mealService = (MealService) ApplicationUtil.getContext().getBean("mealService");
        Meal meal = mealService.getMeal(Integer.parseInt(mealId));



        //生成订单
        if(userId > 0 && meal != null){

            if(!user.getPhone().equals(phone)){
                dto.setErrMsg("手机号与档案信息不一致");
                dto.setLocation("main");
                dto.setStatusCode(201);
            }else if(user.getSex() != Integer.parseInt(sex)){
                dto.setErrMsg("性别与档案信息不一致");
                dto.setLocation("main");
                dto.setStatusCode(201);
            }else if(!user.getRealName().equals(realname)) {
                dto.setErrMsg("真实姓名与档案信息不一致");
                dto.setLocation("main");
                dto.setStatusCode(201);
            }else{
                Order order = new Order();
                order.setOrderSn("dd_"+System.currentTimeMillis());
                order.setCreateTime(BigDecimal.valueOf(System.currentTimeMillis()/1000));
                order.setOrderName(meal.getMealName());
                order.setOrderPrice(meal.getMealPrice());
                order.setMealId(meal.getId());
                order.setUserId(userId);

                order.setReceptionId(adminUser.getId());
                order.setStatus(0);

                //生成订单
                OrderService orderService = (OrderService) ApplicationUtil.getContext().getBean("orderService");
                Integer integer = orderService.addOrder(order);
                int orderId = order.getId();
                if(orderId >0){
                    //生成订单一维码

                    ServletContext servletContext = req.getServletContext();
                    String barcodeData = order.getOrderSn()+""; // 条形码数据
                    String path = BarcodeGeneratorUtil.generateBarcode(servletContext,barcodeData);
                    if(path != null){
                        Integer row = orderService.updateOrder(orderId, path, null);
                        if(row>0){
                            dto.setErrMsg("开单成功");
                            dto.setLocation("meal_list");
                            dto.setStatusCode(200);
                        }else{
                            dto.setErrMsg("更新订单一维码失败");
                            dto.setLocation("main");
                            dto.setStatusCode(201);
                        }
                    }else{
                        dto.setErrMsg("生成订单一维码失败");
                        dto.setLocation("main");
                        dto.setStatusCode(201);
                    }


                }else{
                    dto.setErrMsg("开单失败，请检查填写的信息");
                    dto.setStatusCode(201);
                }
            }

        }else{
            dto.setErrMsg("开单失败，请检查填写的信息");
            dto.setStatusCode(201);

        }


        return dto;
    }

}
